package com.net.oil.user;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.net.oil.R;
import com.net.oil.app.Constant;
import com.net.oil.app.UserInfoManager;
import com.net.oil.base.BaseActivity;
import com.net.oil.base.EventBussMessage;
import com.net.oil.http.AppUrl;
import com.net.oil.user.bean.CheckPhoneBean;
import com.net.oil.user.bean.RegisterBean;
import com.net.oil.user.bean.UserInfo;
import com.net.oil.user.contract.RegisterContract;
import com.net.oil.user.presenter.RegisterPresenter;
import com.net.oil.util.SharedPreferencesKey;
import com.net.oil.util.SharedPreferencesUtil;
import com.net.oil.util.StringUtil;
import com.net.oil.webview.WebViewActivity;
import com.net.oil.widget.ToastUtil;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;

/**
 * 注册
 * 2019-4-20修改：注册采用新的接口，旧的废弃
 */
public class RegisterActivity extends BaseActivity<RegisterPresenter> implements RegisterContract.View {

    @BindView(R.id.toolbar_go_back)
    ImageView toolbarGoBack;
    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    @BindView(R.id.phone_number_et)
    EditText phoneNumberEt;
    @BindView(R.id.get_verify_code_button)
    TextView getVerifyCodeButton;
    @BindView(R.id.verify_code_et)
    EditText verifyCodeEt;
    @BindView(R.id.password_et)
    EditText passwordEt;
    @BindView(R.id.nickname_et)
    EditText nicknameEt;
    @BindView(R.id.register_button)
    Button registerButton;
    @BindView(R.id.invitation_phone_et)
    EditText invitationPhoneEt;
    @BindView(R.id.email_et)
    EditText emailEt;

    private long allTime = 60 * 1000;   //计时器时间
    private long stepTime = 1000;       //计时器每步的时间

    private String phoneNumber;

    private Gson gson;

    //计时器
    CountDownTimer timer = new CountDownTimer(allTime, stepTime) {
        @Override
        public void onTick(long millisUntilFinished) {
            getVerifyCodeButton.setText(String.format(getString(R.string.millis_format), millisUntilFinished / 1000));
            getVerifyCodeButton.setEnabled(false);
        }

        @Override
        public void onFinish() {
            getVerifyCodeButton.setText("重新获取验证码");
            getVerifyCodeButton.setEnabled(true);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        ButterKnife.bind(this);
        presenter = new RegisterPresenter(this);
        gson = new Gson();
        initView();
    }

    private void initView() {
        toolbarTitle.setText(R.string.register);
        toolbarGoBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    /**
     * 验证手机号成功
     *
     * @param checkPhoneBean 返回数据
     */
    @Override
    public void checkPhoneSuccess(CheckPhoneBean checkPhoneBean) {
        dismissProgressDialog();
        if (checkPhoneBean.isExists()) {
            ToastUtil.showErrorToast(this, "手机号已注册");
        } else {
            timer.start();
            getPhoneCodeCode();
        }
    }

    /**
     * 验证手机号失败
     */
    @Override
    public void checkPhoneFailed() {
        dismissProgressDialog();
    }

    /**
     * 获取验证码成功
     */
    @Override
    public void getPhoneCodeSuccess() {

    }

    /**
     * 获取验证码失败
     */
    @Override
    public void getPhoneCodeFailed() {
        timer.cancel();
        timer.onFinish();
    }

    /**
     * 验证验证码成功
     */
    @Override
    public void verifyCodeSuccess() {
        dismissProgressDialog();
        register();
    }

    /**
     * 验证验证码失败
     */
    @Override
    public void verifyCodeFailed() {
        dismissProgressDialog();
    }

    /**
     * 注册成功
     *
     * @param registerBean 返回的数据
     */
    @Override
    public void registerSuccess(RegisterBean registerBean) {
        dismissProgressDialog();
        ToastUtil.showSuccessToast(this, "注册成功");
        if (registerBean != null) {
            SharedPreferencesUtil.setStringParam(this, SharedPreferencesKey.REGISTER_BEAN, gson.toJson(registerBean));
        }

        phoneNumber = phoneNumberEt.getText().toString();
        String password = passwordEt.getText().toString();
        presenter.login(phoneNumber, password);
    }

    /**
     * 注册失败
     */
    @Override
    public void registerFailed() {
        dismissProgressDialog();
    }

    @OnClick({R.id.get_verify_code_button, R.id.register_button, R.id.user_protocol_tv})
    public void onViewClicked(View view) {
        Intent intent = new Intent();
        switch (view.getId()) {
            case R.id.get_verify_code_button:
                checkPhone();       //点击获取验证码先校验手机号，校验手机号成功在获取验证码
                break;
            case R.id.register_button:
                verifyCode();     //点击注册，先验证验证码，验证码ok再调用注册接口
                break;
            case R.id.user_protocol_tv:
                intent.setClass(this, WebViewActivity.class);
                intent.putExtra(Constant.INTENT_TO_WEBVIEW_URL_KEY, AppUrl.ABOUS_US);
                intent.putExtra(Constant.INTENT_IS_SHARE, false);
                startActivity(intent);
                break;
        }
    }

    /**
     * 验证验证码
     */
    private void verifyCode() {
        String phoneNumber = phoneNumberEt.getText().toString();
        String verifyCode = verifyCodeEt.getText().toString();
        if (!StringUtil.isEmpty(phoneNumber)) {
            if (!StringUtil.isEmpty(verifyCode)) {
                showProgressDialog();
                presenter.verifyCode(phoneNumber, verifyCode);
            } else {
                ToastUtil.showErrorToast(this, "请输入验证码");
            }
        } else {
            ToastUtil.showErrorToast(this, "请输入手机号");
        }
    }

    /**
     * 注册
     */
    private void register() {
        String phoneNumber = phoneNumberEt.getText().toString();
        String password = passwordEt.getText().toString();
        String nickname = nicknameEt.getText().toString();
        String invitationPhone = invitationPhoneEt.getText().toString();
        String email = emailEt.getText().toString();

        if (!StringUtil.isEmpty(phoneNumber)) {
            if (!StringUtil.isEmpty(password)) {
                if (password.length() < 6) {
                    ToastUtil.showErrorToast(this, "密码长度至少6位");
                } else {
                    showProgressDialog();
//                    presenter.register(phoneNumber, password, nickname, invitationPhone);     注册 旧接口，废弃，使用新接口
                    presenter.registerV2(phoneNumber, password, nickname, invitationPhone, email);
                }
            } else {
                ToastUtil.showErrorToast(this, "请输入密码");
            }
        } else {
            ToastUtil.showErrorToast(this, "请输入手机号");
        }
    }

    /**
     * 验证手机号
     */
    private void checkPhone() {
        String phoneNumber = phoneNumberEt.getText().toString();
        if (!StringUtil.isEmpty(phoneNumber)) {
            showProgressDialog();
            presenter.checkPhone(phoneNumber);
        } else {
            ToastUtil.showErrorToast(this, "请输入手机号");
        }
    }

    /**
     * 获取验证码
     */
    public void getPhoneCodeCode() {
        String phoneNumber = phoneNumberEt.getText().toString();
        if (!StringUtil.isEmpty(phoneNumber)) {
            timer.start();
            presenter.getPhoneCodeCode(phoneNumber, false);
        }
    }

    /**
     * 登陆成功
     *
     * @param userInfo 返回用户信息
     */
    @Override
    public void loginSuccess(UserInfo userInfo) {
        dismissProgressDialog();
        if (userInfo != null) {
            SharedPreferencesUtil.setStringParam(this, SharedPreferencesKey.PHONE_NUMBER, phoneNumber);
            UserInfoManager.getInstance().setUserInfo(gson.toJson(userInfo));
            ToastUtil.showSuccessToast(this, "登录成功");
            Intent intent = new Intent();
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            Bundle bundle = new Bundle();
            bundle.putSerializable(Constant.LOGIN_RESULT_INTENT_KEY, userInfo);
            intent.putExtras(bundle);
            setResult(RESULT_OK, intent);
            EventBus.getDefault().post(new EventBussMessage(Constant.LOGIN_SUCCESS_CODE, Constant.LOGIN_SUCCESS_MESSAGE));
            finish();
        } else {
            ToastUtil.showErrorToast(this, "登录失败");
        }
    }

    /**
     * 登陆失败
     */
    @Override
    public void loginFailed() {
        dismissProgressDialog();
    }

    /**
     * 注册v2注册成功
     *
     * @param userInfo 返回用户信息
     */
    @Override
    public void registerV2Success(UserInfo userInfo) {
        dismissProgressDialog();
        if (userInfo != null) {
            SharedPreferencesUtil.setStringParam(this, SharedPreferencesKey.PHONE_NUMBER, phoneNumber);
            UserInfoManager.getInstance().setUserInfo(gson.toJson(userInfo));
            ToastUtil.showSuccessToast(this, "注册成功");
            Intent intent = new Intent();
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            Bundle bundle = new Bundle();
            bundle.putSerializable(Constant.LOGIN_RESULT_INTENT_KEY, userInfo);
            intent.putExtras(bundle);
            setResult(RESULT_OK, intent);
            EventBus.getDefault().post(new EventBussMessage(Constant.LOGIN_SUCCESS_CODE, Constant.LOGIN_SUCCESS_MESSAGE));

            if (userInfo.isHasCoupon()){
                /* 如果有优惠券未领取，则发送消息，在mainActivity中接受消息，显示领取优惠券 */
                EventBus.getDefault().post(new EventBussMessage(Constant.HAS_COUPON_CODE, Constant.HAS_COUPON_MESSAGE));
            }
            finish();
        } else {
            ToastUtil.showErrorToast(this, "注册失败");
        }
    }

    /**
     * 注册v2失败
     */
    @Override
    public void registerV2Failed() {
        dismissProgressDialog();
    }
}
